'use strict';

angular.module('snPaas_om')
.directive('spDropdown',['baseUrl','$timeout',function(baseUrl,$timeout){
    return {
      restrict:'A',
      priority:-1,
      templateUrl :baseUrl.static+'template/directive/spDropdown.html',
      replace:true,
      scope:{
         spDropdown: '=',
         spValue: '=',
         spDisplay: '=',
         spId: '='
      },
      // controller:function(){},
      link:function postLink(scope,iElement,iAttrs){
        scope.h = iElement.height();
        if(!scope.spDisplay){
          scope.spDisplay = 'name';
        }
        if(!scope.spId){
          scope.spId = 'id';
        }
        // if(!scope.spDropdown){
        //   alert('sdsd');
        //   scope.spDropdown=[];
        // }
        // if(!scope.spValue){
        //   scope.spValue = 0;
        // }
        scope.baseUrl = baseUrl.static;
        scope.expand = false;

        scope.$watch('spValue',function(n,o){
          // if(n != o){
            if(!scope.spDropdown){
              return;
            }
            for(var i =0,l=scope.spDropdown.length;i<l;i++){
              if(scope.spDropdown[i][scope.spId] == scope.spValue){
                 scope.now = scope.spDropdown[i];
                 break;
              }
            }
          // }
        });
        scope.$watch('spDropdown',function(n,o){
          // if(n != o){
            if(!scope.spDropdown){
              return;
            }
            for(var i =0,l=scope.spDropdown.length;i<l;i++){
              if(scope.spDropdown[i][scope.spId] == scope.spValue){
                 scope.now = scope.spDropdown[i];
                 break;
              }
            }
          // }
        });
        scope.select = function(dropdown){
          scope.now = dropdown;
          console.log(dropdown);
          scope.spValue = dropdown[scope.spId];
        };
        scope.expandFn = function(){
          scope.expand = true;
          iElement.find('.hide-zone').focus();
        };
        iElement.find('.hide-zone').blur(function(){
          $timeout(function(){
            scope.expand = false;
          },200);
        });
      }
   }

}]);